import os

import itchat

from commons.log import LogFactory
from wbot.settings import QR_PIC

logger = LogFactory("login_service").get_logger()


def qr_callback(uuid, status, qrcode):
    """
    服务器上不能显示图片，默认显示图片登录会出异常
    """
    # 手机扫描二维码后，会一直调用qrCallBack函数
    if os.path.exists(QR_PIC):
        return
    with open(QR_PIC, mode='wb') as f:
        f.write(qrcode)
    logger.info("扫描resources下的二维码")


def login_callback():
    try:
        os.remove(QR_PIC)
        logger.info("删除已经登录的二维码图片")
    except:
        logger.info("使用原登录信息登录")
    finally:
        logger.info("登录成功")


def exit_callback():
    logger.info("退出登录")


def get_self_flag():
    """取得自己本次登录的UserName"""
    friends = itchat.get_friends()
    my = friends[0]
    user_name = my.UserName
    return user_name
